﻿using System;
using Hjt212Parser;
using HpSocketIotGateway.Properties;
using log4net;

namespace HpSocketIotGateway.Facade
{
    public class Consumer
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Consumer));
        public static void Consume4Persistence(object state)
        {
            while (true)
            {
                try
                {
                    var info = BufferFacade.DequeueFromMessageQueue();
                    if (BufferFacade.QueueCount() >= 1000)
                    {
                        Log.Error("Waiting to be persist: " + BufferFacade.QueueCount());
                    }
                    if (info != null)
                    {
                        BizPersistence.Persist(info);
                    }
                    if (MyTimer.IsToTheTime("Consumer.Consume4Persistence", 1))
                    {
                        ThreadUtil.Sleep(100);
                        if (Settings.Default.BackupMonthsTo1Table > 0)
                        {
                            BackupProcessedRecord.Delete9999Or0000();
                        }
                        ThreadUtil.Sleep(100);
                        if (Settings.Default.BackupMonthsTo1Table > 0)
                        {
                            BackupProcessedRecord.BackupProcessedMsg();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                finally
                {
                    ThreadUtil.Sleep(10);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }


        public static void Consume4Persistence4GatewayResponse(object state)
        {
            while (true)
            {
                try
                {
                    var info = BufferFacade.DequeueFromMessageQueue4GatewayResponse();
                    if (BufferFacade.QueueCount4GatewayResponse() >= 1000)
                    {
                        Log.Error("Waiting to be persist(GatewayResponse): " + BufferFacade.QueueCount4GatewayResponse());
                    }
                    if (info != null)
                    {
                        BizPersistence.PersistGatewayResponseMsg(info);
                    }
                   
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                finally
                {
                    ThreadUtil.Sleep(10);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }
    }
}
